package com.eportal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.dao.FixApplyEntityMapper;
import com.eportal.dao.FixFixerEntityMapper;
import com.eportal.domain.FixApply;
import com.eportal.domain.FixFixer;
import com.eportal.domain.Sysopt;
import com.eportal.entity.FixApplyEntity;
import com.eportal.entity.FixFixerEntity;
import com.eportal.params.background.Fix.FixParam;
import com.eportal.service.BaseServiceImpl;
import com.eportal.service.FixService;
import com.eportal.util.CityUtil;
import com.eportal.util.ValidateUtil;
import com.eportal.vo.controller.background.fix.ApplyDetailVO;
import com.eportal.vo.controller.background.fix.FixListVO;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("fixService")
public class FixServiceImpl extends BaseServiceImpl<FixFixerEntity> implements FixService{
	private Map<String, Object> result = new HashMap<String, Object>();
	 private Logger log = Logger.getLogger(FixServiceImpl.class);
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private FixFixerEntityMapper fixFixerDao;

	@Resource
	private FixApplyEntityMapper fixApplyDao;

	@Override
	public FixFixer getFixFixer(Long sid){
		FixFixer fixFixer = (FixFixer) dao.getById(FixFixer.class, sid);
		return fixFixer;
	}
	@Override
	public FixApply getFixApply(Long sid){
		FixApply fixApply = (FixApply) dao.getById(FixApply.class, sid);
		return fixApply;
	}
	@Override
	public List<Map<String, Object>> list(JqGridPager jqGridPager) {
		String SQL = "select t.sid,to_char(t.ctime,'yyyy-mm-dd HH24:mi') as ctime,to_char(t.finishTime,'yyyy-mm-dd HH24:mi') as finishTime,t.status,t.type,tu.auname,t.apply_tel as applytel,f.cname as fixname,f.tel as fixtel,c.communityname,c.citycode,a.agtname,r.room_no as room,b.cbname||u.cbname as cbname "
				+ "from FIX_APPLY t "
				+ "left join t04_users tu on tu.userid=t.apply_userid "
				+ "left join fix_fixer f on t.fixer_id=f.sid "
				+ "left join t03_community c on t.communityid=c.sid "
				+ "left join t02_agtent a on t.agtcode=a.sid "
				+ "left join T035_ROOM r on t.room_id=r.sid "
				+ "left join t032_cinstallunit u on r.unit_id=u.sid "
				+ "left join t031_cbuilding b on u.cbuildingid=b.sid ";
	     return dao.query(SQL, jqGridPager);
	}
	@Override
	public List<Map<String, Object>> fixerList(JqGridPager jqGridPager) {
		String SQL = "select t.sid,t.cname,t.type,t.tel,t.introduction,a.havefix,a.nofix,a.likes from FIX_FIXER t "
				+ "left join (select a.fixer_id,nvl(sum(case when a.status=4 then 1 else 0 end),0) as havefix,nvl(sum(case when a.status=3 then 1 else 0 end),0) as nofix,nvl(sum(case when a.like_status=1 then 1 else 0 end),0) as likes from fix_apply a where a.admin_del=1 group by a.fixer_id) a  "
				+ "on a.fixer_id=t.sid";
	     return dao.query(SQL, jqGridPager);
	}
	@Override
	public List<Map<String, Object>> fixerFixList(JqGridPager jqGridPager) {
		String SQL = "select t.sid,to_char(t.ctime,'yyyy-mm-dd HH24:mi') as ctime,to_char(t.finishTime,'yyyy-mm-dd HH24:mi') as finishTime,t.status,t.type,tu.auname,t.apply_tel as applytel,f.cname as fixname,f.tel as fixtel,f.type as fixertype,f.introduction,c.communityname,c.citycode,a.agtname,r.room_no as room,b.cbname||u.cbname as cbname "
				+ "from FIX_APPLY t "
				+ "left join t04_users tu on tu.userid=t.apply_userid "
				+ "left join fix_fixer f on t.fixer_id=f.sid "
				+ "left join t03_community c on t.communityid=c.sid "
				+ "left join t02_agtent a on t.agtcode=a.sid "
				+ "left join T035_ROOM r on t.room_id=r.sid "
				+ "left join t032_cinstallunit u on r.unit_id=u.sid "
				+ "left join t031_cbuilding b on u.cbuildingid=b.sid ";
	     return dao.query(SQL, jqGridPager);
	}
	@Override
	@LogAnnotation(operateDescribe="维修工保存")
	public Map<String, Object> addMethod(FixFixer fixFixer) {
		String msg = ValidateUtil.validate(fixFixer);
	    if (msg == null || msg.trim().length() == 0) {
			try {
				result = new HashMap<String, Object>();
	        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
	        	fixFixer.setType("1");
	        	fixFixer.setAdminDel("1");
	        	fixFixer.setCusername(Long.toString(user.getSid()));
	        	fixFixer.setcTime(new Timestamp(System.currentTimeMillis()));
	        	fixFixer.setAgtCode(user.getAgtCode());
	        	fixFixer.setCommunityId(user.getCommunityId());
	        	save(fixFixer);
	        	result.put("objectId", fixFixer.getSid());
	            result.put("code", 1);
	            result.put("msg", "添加维修工成功");
	        } catch (Exception e) {
	            log.error("添加维修工失败", e);
	            result.put("code", 0);
	            result.put("msg", "添加维修工失败");
	        }
	    } else {
        	result.put("code", 0);
            result.put("msg", msg);
        }
		return result;
	}

	private FixFixer save(FixFixer fixFixer) throws Exception {
		dao.save(fixFixer);
    	return fixFixer;
	}

	@Override
	@LogAnnotation(operateDescribe="维修工修改")
	public Map<String, Object> updateMethod(FixFixer fixFixer) {
		String msg = ValidateUtil.validate(fixFixer);
		result = new HashMap<String, Object>();
		result.put("objectId", fixFixer.getSid());
		if (msg == null || msg.trim().length() == 0) {
			try {
				FixFixer entity = getFixFixer(fixFixer.getSid());
				entity.setCname(fixFixer.getCname());
//				entity.setType(fixFixer.getType());
	        	entity.setTel(fixFixer.getTel());
	        	entity.setIntroduction(fixFixer.getIntroduction());
	        	entity.setAppUserid(fixFixer.getAppUserid());
	        	dao.update(entity);
	            result.put("code", 1);
	            result.put("msg", "修改维修工成功");
	        } catch (Exception e) {
	            log.error("修改维修工失败", e);
	            result.put("code", 0);
	            result.put("msg", "修改维修工失败");
	        }
	    } else {
        	result.put("code", 0);
            result.put("msg", msg);
        }
		 return result;
	}
	@Override
	@LogAnnotation(operateDescribe="维修工删除")
	public Map<String, Object> deleteMethod(String ids) {
		try {
			result = new HashMap<String, Object>();
        	result.put("objectId", ids);
            String[] sparams = ids.split(",");
            FixFixer fixFixer;
            for (String s : sparams) {
            	fixFixer =getFixFixer(Long.parseLong(s));
            	fixFixer.setAdminDel("2");
            	dao.update(fixFixer);
            }
            result.put("code", 1);
            result.put("msg", "删除维修工成功");
        } catch (Exception e) {
            log.error("删除维修工失败", e);
            result.put("code", 0);
            result.put("msg", "删除维修工失败");
        }
        return result;
	}
	@Override
	@LogAnnotation(operateDescribe="报修回复")
	public Map<String, Object> replyMethod(String sid, String fixerId, String fixStartTime, String fixEndTime) {
		try {
			result = new HashMap<String, Object>();
			result.put("objectId", sid);
			FixApply fixApply = getFixApply(Long.parseLong(sid));
			fixApply.setFixerId(fixerId);
			fixApply.setFixStartTime(Timestamp.valueOf(fixStartTime+" 12:00:00"));
			fixApply.setFixEndTime(Timestamp.valueOf(fixEndTime+" 12:00:00"));
			fixApply.setStatus("5");
			fixApply.setReplyTime(new Timestamp(System.currentTimeMillis()));
			dao.update(fixApply);
			result.put("code", 1);
	        result.put("msg", "回复报修成功");
		} catch (Exception e) {
			log.error("回复报修失败", e);
            result.put("code", 0);
            result.put("msg", "回复报修失败");
		}
		return result;
	}
	@Override
	public List<FixFixer> listFixerAll(String hql) {
		return dao.query(hql);
	}
	@Override
	public Map<String, String> getDetailBySql(String sql) {
		List<Map<String, String>> list= null;
		list= dao.queryBySql(sql);
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	@Override
	@LogAnnotation(operateDescribe="用户报修删除")
	public Map<String, Object> deleteFixMethod(String ids) {
		try {
			result = new HashMap<String, Object>();
        	result.put("objectId", ids);
            String[] sparams = ids.split(",");
            FixApply fixApply;
            for (String s : sparams) {
            	fixApply =getFixApply(Long.parseLong(s));
            	fixApply.setAdminDel("2");
            	dao.update(fixApply);
            }
            result.put("code", 1);
            result.put("msg", "删除用户报修成功");
        } catch (Exception e) {
            log.error("删除用户报修失败", e);
            result.put("code", 0);
            result.put("msg", "删除用户报修失败");
        }
        return result;
	}


//todo-----------------------------------------------------------------------------------------------------


	/**
	 * 报修列表
	 *
	 * @param pageEntity 分页对象
	 * @param param      查询参数
	 * @param user       当前用户
	 * @param userRole   当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/23 下午3:34
	 * @see FixServiceImpl#list(JqGridPager)
	 */
	@Override
	public PageInfo<FixListVO> queryForPage(PageEntity pageEntity, FixParam param, Sysopt user, int userRole) {

		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}

		//判断是否是直辖市
		boolean isMunicipalities = false;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getAreaCode())) {
			isMunicipalities = CityUtil.isMunicipalities(param.getAreaCode());
		}
		List<FixListVO> list = fixFixerDao.queryForList(param,isMunicipalities,user,userRole);
		return new PageInfo<>(list);
	}

	/**
	 * 报修详情
	 *
	 * @param sId sId
	 * @return
	 * @author Saber
	 * @Date 2017/8/24 上午9:50
	 * @see com.eportal.action.background.FixAction#applyDetailView()
	 */
	@Override
	public ApplyDetailVO applyDetail(Long sId) {

		return fixFixerDao.getApplyDetail(sId);
	}

	/**
	 * 删除报修
	 *
	 * @param sIds sId集合 用,分割
	 * @return
	 * @author Saber
	 * @Date 2017/8/24 上午10:48
	 * @see FixServiceImpl#deleteFixMethod(String)
	 */
	@Override
	public JSONObject deleteFix(String sIds) {
		JSONObject json = new JSONObject();
		try {
			json.put("objectId", sIds);
			String[] ids = sIds.split(",");
			for (String sId : ids) {
				FixApplyEntity entity = fixApplyDao.selectByPrimaryKey(Long.valueOf(sId));
				entity.setAdminDel("2");
				fixApplyDao.updateByPrimaryKeySelective(entity);
			}
			json.put("code", 1);
			json.put("msg", "删除用户报修成功");
			json.put("data",sIds);
			return json;
		} catch (Exception e) {
			log.error("删除维修工失败", e);
			e.printStackTrace();
			json.put("code", 0);
			json.put("msg", "删除用户报修失败");
			return json;
		}
	}
}
